package com.example.common.network;

import com.example.common.utils.LogUtil;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.Map;

public class HeaderInterceptor implements Interceptor {
    
    private static final String TAG = "HeaderInterceptor";
    
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Request.Builder requestBuilder = originalRequest.newBuilder();
        
        try {
            // 添加所有Header
            HeaderManager headerManager = HeaderManager.getInstance();
            Map<String, String> headers = headerManager.getAllHeaders();
            
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                // 如果原始请求中已经有该Header，则不覆盖（让API调用方可以自定义）
                if (originalRequest.header(entry.getKey()) == null) {
                    requestBuilder.addHeader(entry.getKey(), entry.getValue());
                }
            }
            
            LogUtil.d(TAG, "Added headers to request: " + originalRequest.url());
            
        } catch (IllegalStateException e) {
            LogUtil.w(TAG, "HeaderManager not initialized, using default headers");
            // 如果HeaderManager未初始化，使用基本Header
            addDefaultHeaders(requestBuilder, originalRequest);
        }
        
        Request newRequest = requestBuilder.build();
        return chain.proceed(newRequest);
    }
    
    /**
     * 添加默认Header（当HeaderManager未初始化时使用）
     */
    private void addDefaultHeaders(Request.Builder requestBuilder, Request originalRequest) {
        if (originalRequest.header(NetworkConfig.HEADER_CONTENT_TYPE) == null) {
            requestBuilder.addHeader(NetworkConfig.HEADER_CONTENT_TYPE, NetworkConfig.CONTENT_TYPE_JSON);
        }
        if (originalRequest.header(NetworkConfig.HEADER_ACCEPT) == null) {
            requestBuilder.addHeader(NetworkConfig.HEADER_ACCEPT, NetworkConfig.CONTENT_TYPE_JSON);
        }
    }
}